/*
 * Copyright (c) 2014 laidian. All Rights Reserved.
 * 
 * @author yaoyuming
 * 
 * @date 2020-04-16 16:58
 */
package com.yao.common.helper;

import org.apache.poi.xwpf.usermodel.XWPFDocument;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 文件上传/下载
 * 
 * @author yaoyuming
 * @date 2020/04/16 16:58
 */
public class FileloadHelper {

    public static void download(HttpServletResponse response, InputStream inputStream, String fileName) throws IOException {

        response.setHeader("Content-Disposition", "attachment; filename=" +
                new String(fileName.getBytes(), "ISO-8859-1"));
//        response.setHeader("content-Type", "docx");
        response.setContentType("application/msword");
//        response.setHeader("content-type", "application/octet-stream");

        OutputStream os = null;
        XWPFDocument document;
        try {

//            document = new XWPFDocument(OPCPackage.open(inputStream));
            os = response.getOutputStream();


            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }

            os.flush();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            os.close();
        }

    }

    /**
     * 处理下载时文件名称中文乱码( Edge浏览器乱码 待解决)
     *
     * @param fileName
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String encodeFileName(String fileName) {

        try {
            /*if (RequestHelper.isIEbrowser()) {
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
            }*/
            fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return fileName;
    }
}